/**
 * @author        Nicolas Bottarini <nicolasbottarini@gmail.com>, 404 <http://www.proyecto404.com>
 * @version       $Rev: 3 $
 * @lastrevision  $Date: 2011-09-12 16:45:37 +0000 (Mon, 12 Sep 2011) $	 
 */
package com.proyecto404.core.mvc {
	import com.proyecto404.core.BaseObject;
	import com.proyecto404.core.EventArgs;
	import com.proyecto404.core.configuration.PreloaderInfo;
	import com.proyecto404.core.exception.InvalidOperationException;
	import com.proyecto404.core.exception.InvalidPreloaderClassException;
	import com.proyecto404.core.io.DisplayObjectLoadedEventArgs;
	import com.proyecto404.core.io.DisplayObjectLoader;
	import com.proyecto404.core.util.FileHelper;
	
	import org.osflash.signals.ISignal;
	import org.osflash.signals.Signal;
	
	public class PreloaderLoader extends BaseObject {
		private var _application:Application;
		private var _loadError:Signal;
		private var _loaded:Signal;
		
		public function PreloaderLoader(application:Application) {
			super();
			_application = application;
			_loadError = new Signal(EventArgs);
			_loaded = new Signal(EventArgs);
		}
		
		public function get loadError():ISignal {
			return _loadError;
		}

		public function get loaded():ISignal {
			return _loaded;
		}
		
		public function load(preloaderName:String):void {
			var preloaderInfo:PreloaderInfo = _application.configuration["preloaders: " + preloaderName] as PreloaderInfo;
			var loader:DisplayObjectLoader = new DisplayObjectLoader();
			loader.loaded.addOnce(function(e:DisplayObjectLoadedEventArgs):void {
				var preloaderView:PreloaderView = e.content as PreloaderView;
				if (preloaderView == null) {
					throw new InvalidPreloaderClassException();
				}
				_application.library.storeSwf(FileHelper.getFileName(preloaderInfo.file), preloaderView);
				var preloader:Preloader = new Preloader(_application, preloaderInfo);
				preloader.allLoaded.add(function(e:EventArgs):void {
					preloaderView.close();			
				});
				preloaderView.initialize(_application, preloader);
				preloaderView.opened.add(function(e:EventArgs):void {
					preloader.start();		
				});
				_loaded.dispatch(new PreloaderLoadedEventArgs(preloader, preloaderView));
			});
			loader.loadError.add(function(e:EventArgs):void {
				_loadError.dispatch(new EventArgs());
			});
			loader.load(preloaderInfo.file);
		}
	}
}